package com.xuwang.Util;


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
 * @ Author xuwang
 * @ Date 2021/8/2 12:13
 * @ VERSION 1.0.0
 */

/**
 * @ Desc 将java对象序列化转换为Json
 * @ Params  Object
 * @ Returns  json对象
 * @ Other  静态方法直接调用
 */
public class WriteJson {
    /**
     * 返回JSON
     * @param object
     * @return
     * @throws JsonProcessingException
     */
    public static String getJson(Object object) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(object);
        return json;
    }

    /**
     * 返回response
     * @param object
     * @param response
     * @throws IOException
     */
    public static String getResponse(Object object, HttpServletResponse response) throws IOException {
        response.setContentType("text/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        String json = JSON.toJSONString(object);
        out.println(json);
        out.flush();
        out.close();
        return json;
    }
}
